package com.zsck.pos.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.chinaums.commoncheck.R;
import com.google.gson.Gson;
import com.ums.AppHelper;
import com.ums.anypay.service.IOnTransEndListener;
import com.zsck.pos.base.BaseTitleActivity;
import com.zsck.pos.bean.FeeItem;
import com.zsck.pos.bean.PayData;
import com.zsck.pos.bean.PosResult;
import com.zsck.pos.bean.Record;
import com.zsck.pos.bean.TransData;
import com.zsck.pos.common.Constants;
import com.zsck.pos.net.MyObserver;
import com.zsck.pos.net.RetrofitCilent;
import com.zsck.pos.utils.LogUtil;
import com.zsck.pos.utils.TimeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.zsck.net.Utils.RxHelper.observableIO2Main;

public class RecordActivity extends BaseTitleActivity {

    /*房间号*/
    @BindView(R.id.tv_room)
    TextView mTvRoom;
    /*金额*/
    @BindView(R.id.tv_money)
    TextView mTvMoney;
    /*名字*/
    @BindView(R.id.tv_name)
    TextView mTvName;
    /*费项*/
    @BindView(R.id.tv_cost)
    TextView mTvCost;
    /*账单月份*/
    @BindView(R.id.tv_month)
    TextView mTvMonth;
    /*账单金额*/
    @BindView(R.id.tv_money1)
    TextView mTvMoney1;
    /*账单状态*/
    @BindView(R.id.tv_bill_status)
    TextView mTvBillStatus;
    /*当前状态*/
    @BindView(R.id.tv_cur_status)
    TextView mTvCurStatus;
    /*付款帐户*/
    @BindView(R.id.tv_payment)
    TextView mTvPayment;
    /*收款商户*/
    @BindView(R.id.tv_collection)
    TextView mTvCollection;
    /*支付时间*/
    @BindView(R.id.tv_pay_time)
    TextView mTvPayTime;
    /*支付方式*/
    @BindView(R.id.tv_pay_type)
    TextView mTvPayType;
    /*账单编号*/
    @BindView(R.id.tv_bill_number)
    TextView mTvBillNumber;
    /*支付单号*/
    @BindView(R.id.tv_pay_no)
    TextView mTvPayNo;
    /*撤消*/
    @BindView(R.id.tv_cancel)
    TextView mTvCancel;

    private String mBatchNo;
    private Record mRecord;

    @Override
    public int setLayout() {
        return R.layout.activity_record;
    }

    @Override
    public String setTitle() {
        return "收款明细";
    }

    @Override
    public Activity setActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initEvents();
        initData();
    }


    private void initEvents(){
        mTvCancel.setOnClickListener(this);
    }
    private void initData(){
        Intent intent = getIntent();
        mBatchNo = intent.getStringExtra("batchNo");
        getGetinDetail();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case  R.id.btn_collection:

                break;
            case R.id.tv_cancel:
                validateCancelPosPaid();
                break;
        }
    }


    private void getGetinDetail(){
        Map<String,Object> map = new HashMap<>();
        map.put("batchNo",mBatchNo);
        MyObserver<Record> observer = new MyObserver<Record>(this) {
            @Override
            public void onSuccess(Record result) {
                onGetinDetail(result);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test",e.getMessage());
                Toast.makeText(RecordActivity.this,errorMsg,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void reRequest() {
                getGetinDetail();
            }
        };
        RetrofitCilent.getApiService().getGetinDetail(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }


    private void onGetinDetail(Record result){
        if(result == null){
            return;
        }
        mRecord = result;
        mTvName.setText(result.getCheckInPer());
        mTvRoom.setText(result.getRoomName());
        mTvMoney.setText(result.getTotalFee() + "");
        mTvCost.setText(result.getName());
        mTvMonth.setText(result.getMonth());
        mTvMoney1.setText("¥" + result.getTotalFee());
        mTvBillStatus.setText(result.getBillStatus());
        mTvCurStatus.setText(result.getStatus());
        mTvPayment.setText(result.getPayer());
        mTvCollection.setText(result.getProjectCompanyName());
        mTvPayTime.setText(result.getPayTime());
        if(!TextUtils.isEmpty(result.getPaymentMethod())){
            mTvPayType.setText(result.getPaymentMethod().replace("iPosCardPay","刷卡支付").replace("iPosQrCodePay","二维码支付"));
        }
        mTvBillNumber.setText(result.getCode());
        mTvPayNo.setText(result.getTradeNo());
        mTvMoney.setTextColor(Color.parseColor("支付成功".equals(result.getStatus()) ? "#F0861B" : "#999999"));
    }

    private void callTrans(Record result) {
        if(result == null){
            LogUtil.i("RecordActivity","result is null")          ;
            return;
        }
        String transAppName = "公共资源";
        String transAppId = "撤销";


        JSONObject transData = new JSONObject();
        try {

            transData.put("appId", Constants.APPID);//appId
            transData.put("useScan", false);//
            transData.put("extOrderNo", result.getTradeNo());//extOrderNo
            transData.put("isNeedPrintReceipt",false);//交易完是否自动打印签购单，注意true表示不自动打单，false表示自动打单。若选择打单则将按照银商标准签购单样式打印，若选择不自动打单则可根据支付结果自行调用打印接口打印，请参考SDK脚本打印范例程序。
        } catch (JSONException e) {
            LogUtil.e("Record",e.getMessage());
        }
        //所有的支付应用都通过callTrans调起
        AppHelper.callTrans(this, transAppName, transAppId, transData, listener);
    }

    /**
     * 支付接口调用结果监听**/
    IOnTransEndListener listener = new IOnTransEndListener() {
        @Override
        public void onEnd(String reslutmsg) {//reslutmsg接口调用结果

            PosResult result = new Gson().fromJson(reslutmsg, PosResult.class);
            if(result == null){
                LogUtil.i("RecordActivity","出错了");
                return;
            }
            TransData transData = result.getTransData();
            if(transData == null){
                LogUtil.i("RecordActivity","出错了");
                return;
            }

            if("00".equals(transData.getResCode())){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        cancelPosPaid();
                    }
                });

            }


        }
    };


    private void validateCancelPosPaid(){
        Map<String,Object> map = new HashMap<>();
        map.put("billMonth", TimeUtils.timeMillis(mRecord.getMonth(),"yyyy-MM"));
        map.put("contractId",mRecord.getContractId());
//        map.put("tradeNo",mRecord.getTradeNo());
        List<String> feeIdList = mRecord.getFeeIdList();
        List<String> billIdList = mRecord.getBillIdList();
        List<FeeItem> requestList = new ArrayList<>();
        if(feeIdList != null && billIdList != null){
            for(int i = 0 ; i < feeIdList.size() ; i++){
                FeeItem item = new FeeItem();
                item.id = feeIdList.get(i);
                item.billId = billIdList.get(i % billIdList.size());
                item.name = mRecord.getName();
                item.tradeNo=mRecord.getTradeNo();
                requestList.add(item);
            }
        }

        map.put("requestList",requestList);
        MyObserver<Object> observer = new MyObserver<Object>(this) {
            @Override
            public void onSuccess(Object result) {
                callTrans(mRecord);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test",e.getMessage());
                Toast.makeText(RecordActivity.this,errorMsg,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void reRequest() {
                validateCancelPosPaid();
            }
        };
        RetrofitCilent.getApiService().validateCancelPosPaid(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }


    private void cancelPosPaid(){
        Map<String,Object> map = new HashMap<>();
        map.put("billMonth", TimeUtils.timeMillis(mRecord.getMonth(),"yyyy-MM"));
        map.put("contractId",mRecord.getContractId());
//        map.put("tradeNo",mRecord.getTradeNo());
        List<String> feeIdList = mRecord.getFeeIdList();
        List<String> billIdList = mRecord.getBillIdList();
        List<FeeItem> requestList = new ArrayList<>();
        if(feeIdList != null && billIdList != null){
            for(int i = 0 ; i < feeIdList.size() ; i++){
                FeeItem item = new FeeItem();
                item.id = feeIdList.get(i);
                item.billId = billIdList.get(i % billIdList.size());
                item.name = mRecord.getName();
                item.tradeNo=mRecord.getTradeNo();
                requestList.add(item);
            }
        }

        map.put("requestList",requestList);
        MyObserver<Object> observer = new MyObserver<Object>(this) {
            @Override
            public void onSuccess(Object result) {
                //callTrans(mRecord);
                Toast.makeText(RecordActivity.this,"操作成功",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                ComponentName componentName= new ComponentName("com.ums.sz.pos","com.zsck.pos.activity.RecordsActivity");
                intent.setComponent(componentName);
                startActivity(intent);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test",e.getMessage());
                Toast.makeText(RecordActivity.this,errorMsg,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void reRequest() {
                cancelPosPaid();
            }
        };
        RetrofitCilent.getApiService().cancelPosPaid(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }



}
